package com.example.zhouhao2022050651

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.zhouhao2022050651.databinding.ActivityMainBinding
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.util.ArrayList

class MainActivity : ComponentActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var studentList: ArrayList<Student>

    // 用于启动第二个Activity并获取返回结果的Launcher
    private val startForResultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result: ActivityResult ->
        if (result.resultCode == RESULT_OK && result.data!= null) {
            val newStudent = result.data?.getSerializableExtra("newStudent") as? Student
            if (newStudent!= null) {
                studentList.add(newStudent)
                saveStudentListToFile()
                setupRecyclerView()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 从文件中读取学生列表数据
        studentList = loadStudentListFromFile()

        binding.newperson.setOnClickListener {
            val intent = Intent(this, MainActivity2::class.java)
            startForResultLauncher.launch(intent)
        }

        setupRecyclerView()
    }

    private fun setupRecyclerView() {
        val recyclerView: RecyclerView = binding.recyclerView
        recyclerView.layoutManager = LinearLayoutManager(this)
        val adapter = StudentAdapter(studentList)
        recyclerView.adapter = adapter
    }

    // 从文件中加载学生列表数据
    private fun loadStudentListFromFile(): ArrayList<Student> {
        val file = File(filesDir, "students.dat")
        return if (file.exists()) {
            val fis = FileInputStream(file)
            val ois = ObjectInputStream(fis)
            val studentList = ois.readObject() as ArrayList<Student>
            ois.close()
            fis.close()
            studentList
        } else {
            ArrayList()
        }
    }

    // 将学生列表数据保存到文件
    private fun saveStudentListToFile() {
        val file = File(filesDir, "students.dat")
        val fos = FileOutputStream(file)
        val oos = ObjectOutputStream(fos)
        oos.writeObject(studentList)
        oos.close()
        fos.close()
    }
}